package com.cefa.edu.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.cefa.edu.datasource.DataSourceAspect;
import com.cefa.edu.datasource.DynamicDataSource;
import com.cefa.edu.datasource.DynamicDataSourceHolder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by qimwang on 7/26/17.
 */
@Configuration
@EnableAspectJAutoProxy
public class DatabaseConfig {
    @Value("${datasource.cefaedu.url}")
    String dbUrl;

    @Value("${datasource.cefaedu.username}")
    String dbUserName;

    @Value("${datasource.cefaedu.password}")
    String dbPassword;

    @Bean(name="dataSource")
    public DataSource dataSource()
    {
        DynamicDataSource dataSource = new DynamicDataSource();

        DruidDataSource mcDataSource = new DruidDataSource();
        mcDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        mcDataSource.setUrl(dbUrl);
        mcDataSource.setUsername(dbUserName);
        mcDataSource.setPassword(dbPassword);
        mcDataSource.setInitialSize(10);
        mcDataSource.setMaxActive(50);
        mcDataSource.setMinIdle(8);
        mcDataSource.setTimeBetweenEvictionRunsMillis(60000);
        mcDataSource.setRemoveAbandoned(true);
        mcDataSource.setDefaultAutoCommit(false);

        Map<Object, Object> targetDataSources = new HashMap<>(20);
        targetDataSources.put(DynamicDataSourceHolder.CEFAEDU_DATA_SOURCE, mcDataSource);
        dataSource.setTargetDataSources(targetDataSources);
        dataSource.setDefaultTargetDataSource(mcDataSource);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
    {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }

    @Bean("transactionManager")
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager  transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

    @Bean
    public DataSourceAspect dataSourceAspect()
    {
        return new DataSourceAspect();
    }
}
